package com.cap.dreamcircle.View;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Consts.Constants;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.SolveDreamBean;
import com.cap.dreamcircle.Model.Bean.SolveDreamTalkEntity;
import com.cap.dreamcircle.Model.IDreamModel;
import com.cap.dreamcircle.Model.Impl.DreamModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.SimpleMediaPlayerUtils;
import com.cap.dreamcircle.Utils.TimeUtils;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.cap.dreamcircle.View.Adapter.AdapterSolveDreamTalk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by liucxu on 2017/9/15.
 */

public class SolveDreamActivity extends BaseActivity {

    @BindView(R.id.layout_back)
    LinearLayout layout_back;
    @BindView(R.id.tv_title)
    TextView tv_title;

    @BindView(R.id.imv_post_comment)
    ImageView imv_post_comment;
    @BindView(R.id.edt_post_comment)
    EditText edt_post_comment;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.chat_list)
    ListView chat_list;

    private View header_view;
    private TextView header_tv_dream_content;
    private TextView header_tv_friend_dream_time;
    private RelativeLayout layout_audio;
    private ImageView imv_playing_status_audio;

    private boolean refresh = true;

    private String dreamId = "";
    private String dreamDetail = "";
    private String dreamTime = "";
    private String dreamVoiceUrl = "";

    private IDreamModel dreamModel;
    private AdapterSolveDreamTalk adapter;
    private List<SolveDreamTalkEntity> datas = new ArrayList<>();
    private Subscription mSubscription;

    @Override
    public int getLayoutId() {
        return R.layout.activity_solve_dream;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        dreamDetail = getIntent().getStringExtra("dreamDetail");
        dreamTime = getIntent().getStringExtra("dreamTime");
        dreamVoiceUrl = getIntent().getStringExtra("dreamVoiceUrl");
        dreamId = getIntent().getStringExtra("dreamId");
        if ((TextUtils.isEmpty(dreamDetail) && (TextUtils.isEmpty(dreamVoiceUrl))) || (TextUtils.isEmpty(dreamId))) {
            App.GetInstance().finishActivity(this);
        }
        header_view = View.inflate(this, R.layout.header_solve_dream, null);
        header_tv_dream_content = (TextView) header_view.findViewById(R.id.tv_dream_content);
        header_tv_friend_dream_time = (TextView) header_view.findViewById(R.id.tv_friend_dream_time);
        header_tv_friend_dream_time.setText(TimeUtils.formatTime(dreamTime));
        imv_playing_status_audio = (ImageView) header_view.findViewById(R.id.imv_playing_status_audio);
        layout_audio = (RelativeLayout) header_view.findViewById(R.id.layout_audio);
        if (TextUtils.isEmpty(dreamDetail)) {
            header_tv_dream_content.setVisibility(View.GONE);
        } else {
            header_tv_dream_content.setVisibility(View.VISIBLE);
            header_tv_dream_content.setText(dreamDetail);
        }
        if (TextUtils.isEmpty(dreamVoiceUrl))
            layout_audio.setVisibility(View.GONE);
        else {
            layout_audio.setVisibility(View.VISIBLE);
            imv_playing_status_audio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SimpleMediaPlayerUtils.getInstance(SolveDreamActivity.this).play(Constants.BASE_URL + dreamVoiceUrl, new SimpleMediaPlayerUtils.VoicePlayInterface() {
                        @Override
                        public void onStartPlaying() {
                            imv_playing_status_audio.setImageResource(0);
                            imv_playing_status_audio.setImageDrawable(null);
                            imv_playing_status_audio.setImageURI(null);
                            imv_playing_status_audio.setImageResource(R.mipmap.audio_playing);
                        }

                        @Override
                        public void onPause() {
                            imv_playing_status_audio.setImageResource(0);
                            imv_playing_status_audio.setImageDrawable(null);
                            imv_playing_status_audio.setImageURI(null);
                            imv_playing_status_audio.setImageResource(R.mipmap.audio_pause);
                        }

                        @Override
                        public void onPlayCompleted() {
                            imv_playing_status_audio.setImageResource(0);
                            imv_playing_status_audio.setImageDrawable(null);
                            imv_playing_status_audio.setImageURI(null);
                            imv_playing_status_audio.setImageResource(R.mipmap.audio_pause);
                        }
                    });
                }
            });
        }
        adapter = new AdapterSolveDreamTalk(this, datas);
        chat_list.setAdapter(adapter);
    }

    @Override
    public void setupData() {
        dreamModel = new DreamModelImpl();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refresh = true;
                refreshLayout.setEnableLoadmore(true);
                RequestSolveDreamRecordTalk();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refresh = false;
                RequestSolveDreamRecordTalk();
            }
        });
        RequestSolveDreamRecordTalk();
    }

    private void RequestSolveDreamRecordTalk() {
        String pre_dreamId = "0";
        String last_dreamId = "0";
        if (datas == null || datas.size() == 0) {
            pre_dreamId = "0";
            last_dreamId = "0";
        } else {
            if (refresh) {
                pre_dreamId = datas.get(0).getTimeLineId();
                last_dreamId = "0";
            } else {
                pre_dreamId = "0";
                last_dreamId = datas.get(datas.size() - 1).getTimeLineId();
            }
        }
        dreamModel.RequestSolveDreamRecordTalk(dreamId, pre_dreamId, last_dreamId).compose(TransformUtils.<SolveDreamBean>defaultSchedulers()).subscribe(new CommonSubscriber<SolveDreamBean>() {
            @Override
            public void onSuccess(SolveDreamBean response) {
                refreshLayout.finishRefresh();
                if ((response.getDreamTalk() != null) && (response.getDreamTalk().size() > 0)) {
                    if (!refresh) {
                        datas.addAll(response.getDreamTalk());
                        adapter.setDatas(datas);
                    } else {
                        List<SolveDreamTalkEntity> datas_local = new ArrayList<>();
                        datas_local.addAll(response.getDreamTalk());
                        datas_local.addAll(datas);
                        datas.clear();
                        datas.addAll(datas_local);
                        adapter.setDatas(datas);
                    }
                } else {
                    refreshLayout.finishLoadmore();
                    refreshLayout.setEnableLoadmore(false);
                }
                if (chat_list.getHeaderViewsCount() == 0) {
                    chat_list.addHeaderView(header_view);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                refreshLayout.finishLoadmore();
                if (chat_list.getHeaderViewsCount() == 0) {
                    chat_list.addHeaderView(header_view);
                }
            }
        });
    }

    @OnClick({R.id.layout_back, R.id.imv_post_comment})
    void doClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.layout_back:
                App.GetInstance().finishActivity(this);
                break;
            case R.id.imv_post_comment:
                postComment();
                break;
        }
    }

    private void postComment() {
        if (TextUtils.isEmpty(edt_post_comment.getText().toString())) {
            ToastUtils.showShortToast(this, "请输入回复内容");
        } else {
            dreamModel.PostDreamRecordTalk(dreamId, edt_post_comment.getText().toString()).compose(TransformUtils.<BaseBean>defaultSchedulers()).subscribe(new CommonSubscriber<BaseBean>() {
                @Override
                public void onSuccess(BaseBean response) {
                    edt_post_comment.setText("");
                    refresh = false;
                    RequestSolveDreamRecordTalk();
                }

                @Override
                public void onFailure(BaseBean response) {

                }
            });
        }
    }

    @Override
    protected void onStop() {
        SimpleMediaPlayerUtils.getInstance(this).releaseMediaPlayer();
        if(mSubscription!=null){
            mSubscription.unsubscribe();
        }
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mSubscription == null) {
            mSubscription = Observable.interval(10000, 30000, TimeUnit.MILLISECONDS)
                    //延时3000 ，每间隔3000，时间单位
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            refresh = false;
                            RequestSolveDreamRecordTalk();
                        }
                    });
        }
    }
}
